import { useFavoriteGame } from "@/features/business/HomePage_deprecated/atoms_deprecated"
import { useEnterGame } from "@/pages/HomePage/hooks/useEnterGame"
import { getAssetsUrlWithHttp } from "@/features/business/HomePage_deprecated/constant"
import { resolveAssetImage } from "@/utils/common"
import styled from "@emotion/styled"
import { useAtom } from "jotai"
import { SyntheticEvent, useEffect } from "react"
import { Link } from "react-router-dom"
import { activeCategoryAtom, categoryTitleAtom, gameImagesAtom } from "../atom"
import FavEmpty from "./FavEmpty"

const GamesContainer = styled.div`
    width: 351rem;
    height: 234rem;
    margin: 0 auto;
    background-color: #ffffff;
    border-radius: 10rem;
    position: relative;
    z-index: 1;
`

const CategoryTabs = styled.div`
    display: flex;
    align-items: center;
    padding-top: 12rem;
    margin-bottom: 12rem;
    margin-left: 12rem;
    /* gap: 24rem; */
`

interface isActive {
    isActive: boolean
}

const CategoryTab = styled.div<isActive>`
    font-family: "Gilroy";
    font-weight: ${(props) => (props.isActive ? 700 : 500)};
    font-size: 16rem;
    margin-right: 24rem;
    color: ${(props) => (props.isActive ? "#000000" : "#69728C")};
    position: relative;
    cursor: pointer;
    padding-bottom: 4rem;
    &::after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: ${(props) => (props.isActive ? "24rem" : "0")};
        height: 2rem;
        background-color: #ff2d55;
        transition: width 0.3s ease;
    }
`

const ImageGrid = styled.div`
    display: flex;
    margin-left: 12rem;
`

const ImageItem = styled.div`
    width: 105rem;
    text-align: center;
    margin-right: 6rem;
`

const GameImage = styled.img`
    width: 105rem;
    height: 138rem;
    border-radius: 6rem;
    object-fit: cover;
`

const ViewMore = styled(Link)`
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
    width: 327rem;
    height: 24rem;
    margin: 12rem auto 0;
    font-family: "Gilroy";
    font-weight: 500;
    font-size: 12rem;
    color: #131416;
    cursor: pointer;
    text-decoration: none;
    &::after {
        content: "→";
        margin-left: 3rem;
    }
`

const CategorySwitch: React.FC = () => {
    const [activeCategoryIndex, setActiveCategoryIndex] = useAtom(activeCategoryAtom)
    const [categoryTitle, setcategoryTitle] = useAtom(categoryTitleAtom)
    const [images, setImages] = useAtom(gameImagesAtom)

    const currentCategoryTitle = categoryTitle[activeCategoryIndex]?.title || ""

    useEffect(() => {
        const fetchImages = {
            recentlyPlayed: [
                {
                    src: resolveAssetImage("pages/UserCenterPage/img_not_found.webp"),
                    alt: "Not Found",
                    name: "Image Not Found",
                },
            ],
            favorite: [],
        }
        // 设置类目
        // setcategoryTitle([{ title: "Recently played" }, { title: "Favorite" }])
        setcategoryTitle([{ title: "Favorite" }])

        // 动态加载图片数据
        const loadImages = async () => {
            try {
                const data = fetchImages
                setImages(data) // 更新 imagesAtom
            } catch (error) {
                setImages({
                    recentlyPlayed: [],
                    favorite: [],
                })
            }
        }

        loadImages()
    }, [setcategoryTitle, setImages])

    const { favoriteList } = useFavoriteGame()
    const { handleEnterGame } = useEnterGame()

    return (
        <GamesContainer>
            <CategoryTabs>
                {categoryTitle.map((category, index) => (
                    <CategoryTab
                        key={index}
                        isActive={activeCategoryIndex === index}
                        onClick={() => setActiveCategoryIndex(index)}
                    >
                        {category.title}
                    </CategoryTab>
                ))}
            </CategoryTabs>
            {currentCategoryTitle === "Recently played" ? (
                images.recentlyPlayed.length > 0 && (
                    <>
                        <ImageGrid>
                            {images.recentlyPlayed.map((image, idx) => (
                                <ImageItem key={idx}>
                                    <GameImage
                                        src={image.src}
                                        onError={(e: SyntheticEvent<HTMLImageElement, Event>) => {
                                            const fallbackSrc = resolveAssetImage(
                                                "pages/UserCenterPage/img_not_found.webp",
                                            )
                                            if (e.currentTarget.src !== fallbackSrc) {
                                                e.currentTarget.src = fallbackSrc
                                            }
                                        }}
                                    />
                                </ImageItem>
                            ))}
                        </ImageGrid>
                        <ViewMore to="/s-game/sections/favorite">View More</ViewMore>
                    </>
                )
            ) : favoriteList.length > 0 ? (
                <>
                    <ImageGrid>
                        {favoriteList.map((favorite, index) => {
                            if (index > 2) {
                                return null
                            }
                            return (
                                <ImageItem key={index}>
                                    <GameImage
                                        onClick={() => {
                                            if (favorite.code) {
                                                handleEnterGame(favorite.code, true)
                                            }
                                        }}
                                        src={getAssetsUrlWithHttp(favorite.img)}
                                        alt={""}
                                        onError={(e: SyntheticEvent<HTMLImageElement, Event>) => {
                                            const fallbackSrc = resolveAssetImage(
                                                "pages/UserCenterPage/img_not_found.webp",
                                            )
                                            if (e.currentTarget.src !== fallbackSrc) {
                                                e.currentTarget.src = fallbackSrc
                                            }
                                        }}
                                    />
                                </ImageItem>
                            )
                        })}
                    </ImageGrid>
                    <ViewMore to="/s-game/sections/favorite">View More</ViewMore>
                </>
            ) : (
                <FavEmpty />
            )}
        </GamesContainer>
    )
}

export default CategorySwitch
